/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年1月6日 下午3:33:33
 */
package com.lenovo.lmrp.server.assigntracer.util.pusher;

import java.util.LinkedList;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.lenovo.lmrp.server.assigntracer.scheduler.RetryPushMessageTask;
import com.lenovo.lmrp.server.assigntracer.util.cache.AssignTracerCache;
import com.lenovo.lmrp.server.assigntracer.util.pusher.ISender.SendResult;
import com.lenovo.sdc.framework.mq.AMQClient;
import com.lenovo.sdc.framework.scheduler.ScheduleTaskManager;
import com.lenovo.sdc.framework.util.AttributeBean;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author songyz
 *
 */
public class GeTuiSender implements ISender {

	private static final Logger logger = LoggerFactory.getLogger(GeTuiSender.class);
//	private LinkedList<PushParameter> pushParameterList = new LinkedList<PushParameter>();
	private AttributeBean params;
	private IGtPush push;
	private AMQClient mqClient;

	@Inject
	public void set(AMQClient mqClient) {
		this.mqClient = mqClient;
	}

	@Inject
	public void set(AttributeBean params) {
		this.params = params;
	}

	@Inject
	public GeTuiSender(AttributeBean params) {
		this.params = params;
		String proxyHost = params.getAttribute("http.proxy.ip", "");
		String proxyPort = params.getAttribute("http.proxy.port", "");
		if (CommonUtil.nonNullAndEmpty(proxyHost) && CommonUtil.nonNullAndEmpty(proxyPort)) {
			System.setProperty("http.proxyHost", proxyHost);
			System.setProperty("http.proxyPort", proxyPort);
		}
		push = new IGtPush(params.getAttribute("geTui.host", "http://sdk.open.api.igexin.com/serviceex"),
				params.getAttribute("geTui.appKey", "s50xUUFOK28NGCSpm4nVv2"),
				params.getAttribute("geTui.master", "6qdW3B9vet9adpIoHTIdz7"));
	}

	public Runnable addMessageToList(PushParameter msParameter) {
//		this.pushParameterList.addLast(msParameter);
		return new pushMessage(msParameter);
	}

	public void SendMessage(PushParameter pushParameter) {
		TransmissionTemplate template = new TransmissionTemplate();
		template.setAppId(params.getAttribute("geTui.appId", "q5mUcjkb8I8HlbDSmpBoh2"));
		template.setAppkey(params.getAttribute("geTui.appKey", "s50xUUFOK28NGCSpm4nVv2"));

		// 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
		template.setTransmissionType(2);

		String content = pushParameter.getContent();
		String title = pushParameter.getTitle();
		String desc = pushParameter.getDesc();
		int getuiType = pushParameter.getGetuiType();
		GeTuiTemplete geTuiTemplete = new GeTuiTemplete();
		geTuiTemplete.setContent(content);
		geTuiTemplete.setTitle(title);
		geTuiTemplete.setDesc(desc);
		geTuiTemplete.setType(getuiType);
		try {
			template.setTransmissionContent(JSONHelper.toJSON(geTuiTemplete));
		} catch (Exception e) {
			throw new TraceableException(ErrorCode.COMM_PARSE_FAILED, e);
		}

		SingleMessage message = new SingleMessage();
		message.setOffline(true);
		// 离线有效时间，单位为毫秒，可选
		message.setOfflineExpireTime(Long.parseLong(params.getAttribute("geTui.message.offLineTime", "86400000")));
		message.setData(template);
		message.setPushNetWorkType(0); // 可选。判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
		Target target = new Target();
		target.setAppId(params.getAttribute("geTui.appId", "q5mUcjkb8I8HlbDSmpBoh2"));
		target.setClientId(pushParameter.getcId());
		IPushResult ret = push.pushMessageToSingle(message, target);

		logger.info("GeTuiSender send result.engineerid is:[{}{}], response:{},messageContent:{} ",
				pushParameter.getEngineerId(), pushParameter.getcId(),ret.getResponse(), pushParameter.getContent());
		
		if ("ok".equals(ret.getResponse().get("result"))) {
			sendMQMessage(mqClient, pushParameter, SendResult.SEND_SUCCEED.getResult());
		} else {
			sendMQMessage(mqClient, pushParameter, SendResult.SEND_FAILD.getResult());
			this.retryPushMessage(pushParameter);
		}
	}
	/**
	 * 个推失败重发
	 */
	@Override
	public void retryPushMessage(PushParameter pushParameter) {
	    logger.warn("GtSender failed. engineer is {},cid is {},content is {}", pushParameter.getEngineerId(),
            pushParameter.getcId(), pushParameter.getContent());
	    sendMQMessage(mqClient, pushParameter, SendResult.SEND_FAILD.getResult());
	    RetryPushMessageTask retryGtMessageTask = new RetryPushMessageTask(pushParameter, params);
        ScheduleTaskManager.getDefaultSchduler().scheduleTask(retryGtMessageTask);
	}

//	public void run() {
//		PushParameter pushParameter = this.pushParameterList.getFirst();
//		this.pushParameterList.removeFirst();
//		SendMessage(pushParameter);
//	}
	
	private class pushMessage implements Runnable {
        
        private PushParameter msParameter;
        
        public pushMessage(PushParameter msParameter) {
            this.msParameter = msParameter;
        }
        @Override
        public void run() {
            SendMessage(msParameter);
        }
    }
}
